<template>
  <el-autocomplete
    class="fi-autocomplete"
    v-model="inputValue"
    :value-key="valueKey"
    v-bind="$attrs"
    v-on="$attrs"
    :fetch-suggestions="querySearch"
    clearable
    @change="handleChange"
    @select="handleSelect"
    @focus="handleVisibleChange"
    ref="autocompleteRef"
  >
    <template #default="{ item }">
      <slot name="default" :item="item">
        {{ item[valueKey] }}
      </slot>
    </template>
    <!-- 其他自定义slot -->
    <template #prefix>
      <slot name="prefix" />
    </template>
    <template #suffix>
      <slot name="suffix" />
    </template>
    <!-- <template #prepend>
      <slot name="prepend" />
    </template>
    <template #append>
      <slot name="append" />
    </template> -->
    <template #loading>
      <slot name="loading" />
    </template>
  </el-autocomplete>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, PropType, computed, watch, nextTick } from 'vue'
import { apiRequestPost } from '@/api/globalApi.js'
// import type { PageConfig } from '@/types/components'

const props = defineProps({
  apiUrl: {
    type: String,
    default: '',
  },
  pageSize: {
    type: Number,
    default: 999,
  },
  valueKey: {
    type: String,
    default: 'value',
  },
  valueKey2: {
    type: String,
    default: 'value',
  },
  // 展示/搜索对象的属性的值，或集合
  valueKeys: {
    type: [String, Array],
    default: '',
    requried: true,
  },
  // 展示对象的属性值或集合
  displayKey: {
    type: String,
    default: 'display',
  },
  // 其他value值数组，搜索时使用
  valueKeyArr: {
    type: Array as PropType<string[]>,
    default: () => [],
  },
  dataArr: {
    type: Array,
    default: () => [],
  },
})
const emits = defineEmits(['change', 'select', 'update:dataArr', 'action-click'])
const state = reactive({
  query: {
    current: 1,
    size: props.pageSize,
  },
  dataList: [],
})
const inputValue = ref('')
watch(
  () => props.dataArr,
  (newValue, oldValue) => {
    if (newValue.length > 0) {
      state.dataList = newValue
    }
    // emits('update:dataArr', newValue)
  },
  { deep: true } // 开启深度监听，因为数组或对象内部属性的改变浅层监听可能无法捕获
)
// let visible: any = computed({
//   get() {
//     return props.modelValue
//   },
//   set(val) {
//     emits('update:modelValue', val)
//   },
// })
const handleChange = (val: any) => {
  emits('change', val)
  state.query[props.queryKey] = val
  console.log('handleChange', val)
}
const handleSelect = (item: Record<string, any>) => {
  emits('select', item)
  console.log(item, '---', state, inputValue.value)
}
const handleScroll = () => {
  console.log('handleScroll')
}
let timeout: ReturnType<typeof setTimeout>
const querySearch = (queryString: string, cb: (arg: any) => void) => {
  console.log(state.dataList,'state.dataList')
  const results = queryString ? state.dataList.filter(createFilter(queryString)) : state.dataList
  clearTimeout(timeout)
  timeout = setTimeout(() => {
    cb(results)
  }, 300)
}
// const createFilter = (queryString: string) => {
//   return (restaurant: any) => {
//     console.log('restaurant.value--', restaurant[props.valueKey], queryString)
//     return restaurant[props.valueKey].toLowerCase().indexOf(queryString.toLowerCase()) === 0
//   }
// }
const createFilter = (queryString: string) => {
  return (restaurant: any) => {
    const searchValue = queryString.toLowerCase()
    const keysToSearch = new Set<string>()

    // 添加props.valueKey到集合中
    if (props.valueKey) {
      keysToSearch.add(props.valueKey)
    }
    if (props.valueKey2) {
      keysToSearch.add(props.valueKey2)
    }


    // 如果props.valueKeyArr存在且不为空，将其内容添加到集合中
    if (Array.isArray(props.valueKeyArr)) {
      props.valueKeyArr.forEach((key) => keysToSearch.add(key))
    }

    // 遍历所有需要检查的key，判断是否匹配
    return Array.from(keysToSearch).some((key) => {
      return restaurant[key]?.toString().toLowerCase().includes(searchValue)
    })
  }
}
const loadMore = (type?: string, columnsVal?: any) => {
  // const obj = initSearchData(type, columnsVal, columns, state.query)
  // state.query = obj.queryData
  // columns.values = obj.columns

  // state.query.current = pageConfig.currentPage
  // isTableLoading.value = true
  // if (pageConfig.pageSize) state.query.size = pageConfig.pageSize

  apiRequestPost(props.apiUrl, state.query)
    .then((res) => {
      // isTableLoading.value = false
      if (res.data.success) {
        state.dataList = res.data.data.result
        // pageConfig.pageSize = Number(res.data.data.size)
        // pageConfig.total = Number(res.data.data.count)
      }
    })
    .catch((error: any) => {
      // isTableLoading.value = false
      // 处理错误
    })
}
const autocompleteRef = ref(null)
// let suggestionsContainer = null
const handleVisibleChange = (visible) => {
  console.log('visible------', visible)
  // if (visible) {
  // nextTick(() => {
  //   // 假设下拉列表的类名为 .el-autocomplete-suggestion__wrap
  //   // suggestionsContainer = autocompleteRef.value.inputRef.querySelector('.el-autocomplete-suggestion__wrap')
  //   // suggestionsContainer = autocompleteRef.value?.popperRef.popperRef
  //   console.log('visible------001', autocompleteRef.value, suggestionsContainer)
  //   // if (suggestionsContainer) {
  //   autocompleteRef.value.addEventListener('scroll', handleScroll)
  //   // }
  // })
  // } else {
  //   if (suggestionsContainer) {
  //     suggestionsContainer.removeEventListener('scroll', handleScroll)
  //     suggestionsContainer = null
  //   }
  // }
}
onMounted(() => {
  if (props.dataArr && props.dataArr.length > 0) {
    state.dataList = props.dataArr
  } else {
    state.query[props.queryKey] = ''
    if (props.apiUrl) loadMore()
  }
})
// const vScrollLoad = {
//   mounted(el, binding, vnode) {
//     console.log('handleScroll----00001', el)
//     function handleScroll(e) {
//       let isBottom = e.target.clientHeight + e.target.scrollTop >= e.target.scrollHeight - 40
//       if (isBottom && !vnode.context.loading) {
//         binding.value()
//       }
//     }
//     // 监听滚动
//     let wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
//     el.__handleScroll__ = handleScroll
//     el.__wrapDom__ = wrapDom
//     wrapDom.addEventListener('scroll', handleScroll, false)
//   },
//   unmounted(el) {
//     // 解除事件监听
//     el.__wrapDom__.removeEventListener('scroll', el.__handleScroll__, false)
//   },
// }
</script>
<style lang="less" scoped>
.fi-autocomplete {
  ::v-deep(.el-autocomplete-suggestion) {
    background: red;
    li:hover {
      background-color: var(--el-color-primary-light-9) !important;
    }
  }
}
</style>
